<template>
  <div class="menu-management-container">
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <span>菜单管理</span>
          <el-button type="primary" @click="handleAddMenu">新增菜单</el-button>
        </div>
      </template>
      
      <!-- 菜单表格 -->
      <el-table
        :data="menus"
        row-key="id"
        border
        default-expand-all
        :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
        v-loading="loading"
      >
        <el-table-column prop="name" label="菜单名称" width="180" />
        <el-table-column prop="path" label="路由路径" width="180" />
        <el-table-column prop="component" label="组件路径" />
        <el-table-column prop="permission" label="权限标识" width="180" />
        <el-table-column prop="type" label="类型" width="100">
          <template #default="scope">
            <el-tag :type="scope.row.type === 0 ? 'primary' : scope.row.type === 1 ? 'success' : 'info'">
              {{ scope.row.type === 0 ? '目录' : scope.row.type === 1 ? '菜单' : '按钮' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="icon" label="图标" width="100">
          <template #default="scope">
            <el-icon v-if="scope.row.icon">
              <component :is="scope.row.icon" />
            </el-icon>
            <span v-else>-</span>
          </template>
        </el-table-column>
        <el-table-column prop="orderNum" label="排序" width="80" />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="scope">
            <el-tag :type="scope.row.status ? 'success' : 'danger'">
              {{ scope.row.status ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="260">
          <template #default="scope">
            <el-button 
              size="small" 
              v-if="scope.row.type !== 2"
              @click="handleAddChild(scope.row)"
            >
              新增
            </el-button>
            <el-button 
              size="small" 
              type="primary" 
              @click="handleEdit(scope.row)"
            >
              编辑
            </el-button>
            <el-button 
              size="small" 
              :type="scope.row.status ? 'warning' : 'success'"
              @click="handleStatusChange(scope.row)"
            >
              {{ scope.row.status ? '禁用' : '启用' }}
            </el-button>
            <el-button 
              size="small" 
              type="danger" 
              @click="handleDelete(scope.row)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    
    <!-- 菜单表单对话框 -->
    <el-dialog 
      v-model="dialogVisible" 
      :title="formTitle" 
      width="600px"
    >
      <el-form 
        :model="menuForm" 
        :rules="rules" 
        ref="menuFormRef" 
        label-width="100px"
      >
        <el-form-item label="上级菜单">
          <el-tree-select
            v-model="menuForm.parentId"
            :data="menuTree"
            check-strictly
            node-key="id"
            :render-after-expand="false"
            :props="{
              label: 'name',
              children: 'children'
            }"
            placeholder="请选择上级菜单"
            clearable
          />
        </el-form-item>
        <el-form-item label="菜单类型" prop="type">
          <el-radio-group v-model="menuForm.type">
            <el-radio :label="0">目录</el-radio>
            <el-radio :label="1">菜单</el-radio>
            <el-radio :label="2">按钮</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="菜单名称" prop="name">
          <el-input v-model="menuForm.name" placeholder="请输入菜单名称" />
        </el-form-item>
        <el-form-item 
          label="路由路径" 
          prop="path"
          v-if="menuForm.type !== 2"
        >
          <el-input v-model="menuForm.path" placeholder="请输入路由路径" />
        </el-form-item>
        <el-form-item 
          label="组件路径" 
          prop="component"
          v-if="menuForm.type === 1"
        >
          <el-input v-model="menuForm.component" placeholder="请输入组件路径" />
        </el-form-item>
        <el-form-item 
          label="权限标识" 
          prop="permission"
          v-if="menuForm.type === 1 || menuForm.type === 2"
        >
          <el-input v-model="menuForm.permission" placeholder="请输入权限标识" />
        </el-form-item>
        <el-form-item 
          label="图标" 
          prop="icon"
          v-if="menuForm.type !== 2"
        >
          <el-input v-model="menuForm.icon" placeholder="请输入图标名称" />
        </el-form-item>
        <el-form-item label="排序" prop="orderNum">
          <el-input-number v-model="menuForm.orderNum" :min="0" :max="999" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-switch v-model="menuForm.status" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { menuAPI } from '@/api/api'
import * as ElementPlusIconsVue from '@element-plus/icons-vue'

export default {
  name: 'MenuManagement',
  components: {
    ...ElementPlusIconsVue
  },
  setup() {
    // 数据定义
    const menus = ref([])
    const loading = ref(false)
    
    // 表单相关
    const dialogVisible = ref(false)
    const menuFormRef = ref(null)
    const menuForm = reactive({
      id: null,
      parentId: null,
      name: '',
      path: '',
      component: '',
      permission: '',
      icon: '',
      type: 1,
      orderNum: 0,
      status: true
    })
    
    // 表单标题计算属性
    const formTitle = computed(() => {
      if (menuForm.id) {
        return '编辑菜单'
      } else if (menuForm.parentId) {
        return '新增子菜单'
      } else {
        return '新增菜单'
      }
    })
    
    // 表单验证规则
    const rules = {
      name: [
        { required: true, message: '请输入菜单名称', trigger: 'blur' },
        { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
      ],
      path: [
        { required: true, message: '请输入路由路径', trigger: 'blur' }
      ],
      component: [
        { required: true, message: '请输入组件路径', trigger: 'blur' }
      ]
    }
    
    // 菜单树数据（用于选择上级菜单）
    const menuTree = ref([])
    
    // 获取菜单树
    const fetchMenuTree = async () => {
      loading.value = true
      try {
        const response = await menuAPI.getMenuTree()
        
        if (response.success) {
          // 添加一个顶级节点，作为根菜单
          const rootMenu = {
            id: 0,
            name: '顶级菜单',
            children: response.data || []
          }
          menuTree.value = [rootMenu]
          
          // 更新表格数据
          menus.value = response.data || []
        } else {
          ElMessage.error('获取菜单列表失败: ' + response.message)
        }
      } catch (error) {
        console.error('获取菜单列表失败:', error)
        ElMessage.error('获取菜单列表失败: ' + (error.message || '未知错误'))
      } finally {
        loading.value = false
      }
    }
    
    // 新增菜单
    const handleAddMenu = () => {
      resetForm()
      menuForm.parentId = 0 // 默认为顶级菜单
      dialogVisible.value = true
    }
    
    // 新增子菜单
    const handleAddChild = (row) => {
      resetForm()
      menuForm.parentId = row.id
      menuForm.type = row.type === 0 ? 1 : 2 // 如果父级是目录，则子菜单为菜单；如果父级是菜单，则子菜单为按钮
      dialogVisible.value = true
    }
    
    // 编辑菜单
    const handleEdit = (row) => {
      resetForm()
      
      // 复制行数据到表单
      Object.assign(menuForm, {
        id: row.id,
        parentId: row.parentId,
        name: row.name,
        path: row.path,
        component: row.component,
        permission: row.permission,
        icon: row.icon,
        type: row.type,
        orderNum: row.orderNum,
        status: row.status
      })
      
      dialogVisible.value = true
    }
    
    // 提交表单
    const submitForm = async () => {
      if (!menuFormRef.value) return
      
      menuFormRef.value.validate(async (valid) => {
        if (valid) {
          try {
            const formData = { ...menuForm }
            
            const response = menuForm.id
              ? await menuAPI.updateMenu(formData)
              : await menuAPI.addMenu(formData)
            
            if (response.success) {
              ElMessage.success(menuForm.id ? '编辑菜单成功' : '新增菜单成功')
              dialogVisible.value = false
              fetchMenuTree()
            } else {
              ElMessage.error((menuForm.id ? '编辑菜单失败: ' : '新增菜单失败: ') + response.message)
            }
          } catch (error) {
            console.error(menuForm.id ? '编辑菜单失败:' : '新增菜单失败:', error)
            ElMessage.error((menuForm.id ? '编辑菜单失败: ' : '新增菜单失败: ') + (error.message || '未知错误'))
          }
        }
      })
    }
    
    // 重置表单
    const resetForm = () => {
      if (menuFormRef.value) {
        menuFormRef.value.resetFields()
      }
      
      menuForm.id = null
      menuForm.parentId = null
      menuForm.name = ''
      menuForm.path = ''
      menuForm.component = ''
      menuForm.permission = ''
      menuForm.icon = ''
      menuForm.type = 1
      menuForm.orderNum = 0
      menuForm.status = true
    }
    
    // 改变菜单状态
    const handleStatusChange = async (row) => {
      try {
        const response = await menuAPI.updateMenuStatus(row.id, !row.status)
        
        if (response.success) {
          ElMessage.success(`${row.status ? '禁用' : '启用'}菜单成功`)
          row.status = !row.status
        } else {
          ElMessage.error(`${row.status ? '禁用' : '启用'}菜单失败: ` + response.message)
        }
      } catch (error) {
        console.error(`${row.status ? '禁用' : '启用'}菜单失败:`, error)
        ElMessage.error(`${row.status ? '禁用' : '启用'}菜单失败: ` + (error.message || '未知错误'))
      }
    }
    
    // 删除菜单
    const handleDelete = (row) => {
      // 检查是否存在子菜单
      if (row.children && row.children.length > 0) {
        ElMessage.warning('该菜单下存在子菜单，无法删除')
        return
      }
      
      ElMessageBox.confirm(
        `确定要删除菜单"${row.name}"吗？`,
        '警告',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }
      )
        .then(async () => {
          try {
            const response = await menuAPI.deleteMenu(row.id)
            
            if (response.success) {
              ElMessage.success('删除菜单成功')
              fetchMenuTree()
            } else {
              ElMessage.error('删除菜单失败: ' + response.message)
            }
          } catch (error) {
            console.error('删除菜单失败:', error)
            ElMessage.error('删除菜单失败: ' + (error.message || '未知错误'))
          }
        })
        .catch(() => {
          ElMessage.info('已取消删除')
        })
    }
    
    // 生命周期钩子
    onMounted(() => {
      fetchMenuTree()
    })
    
    return {
      menus,
      loading,
      dialogVisible,
      menuFormRef,
      menuForm,
      rules,
      menuTree,
      formTitle,
      handleAddMenu,
      handleAddChild,
      handleEdit,
      submitForm,
      handleStatusChange,
      handleDelete
    }
  }
}
</script>

<style scoped>
.menu-management-container {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
</style> 